package com.zhuizikejithreeig.cn.threeigkeji.mianinfo;


import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhuizikejithreeig.cn.adapter.WalletActivityAdapter;
import com.zhuizikejithreeig.cn.been.PayBeen;
import com.zhuizikejithreeig.cn.been.WalletBeen;
import com.zhuizikejithreeig.cn.content.ContectUtils;
import com.zhuizikejithreeig.cn.content.UriContect;
import com.zhuizikejithreeig.cn.threeigkeji.BasicActivity;
import com.zhuizikejithreeig.cn.threeigkeji.CompontApplayCation;
import com.zhuizikejithreeig.cn.threeigkeji.R;
import com.zhuizikejithreeig.cn.utils.GsonUtil;
import com.zhuizikejithreeig.cn.utils.MD5;
import com.zhuizikejithreeig.cn.utils.ToastMake;
import com.zhuizikejithreeig.cn.utils.Utils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import fr.arnaudguyon.xmltojsonlib.JsonToXml;
import fr.arnaudguyon.xmltojsonlib.XmlToJson;
import okhttp3.Call;
import okhttp3.MediaType;

public class WalletActivity extends BasicActivity  {

    private TextView              mMoney;
    private TextView              mTakemoney;
    private RecyclerView          mRecycleview;
    private WalletActivityAdapter mAdapter;
    private List<WalletBeen.DataBean> mList = new ArrayList<>();
    private SmartRefreshLayout mRefreshLayout;
    private TextView           mText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_wallet);
        setLeftShow(3, R.mipmap.message);
        //点击小人去登录界面
        getLift_V().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mMoney = (TextView) findViewById(R.id.money);
        mText = (TextView) findViewById(R.id.text);
        mTakemoney = (TextView) findViewById(R.id.takemoney);
        mRecycleview = (RecyclerView) findViewById(R.id.recycleview);


        //下拉刷新
        mRefreshLayout = (SmartRefreshLayout) findViewById(R.id.smartrefreshlayout);
        mRefreshLayout.setRefreshHeader(new ClassicsHeader(WalletActivity.this));
        //下拉刷新
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mRefreshLayout.finishRefresh();
            }
        });

        //上拉加载更多
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                mRefreshLayout.finishLoadmore();
            }
        });

        //点击提取现金
        mTakemoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //发起微信登录
                String mOpenId = Utils.getString(ContectUtils.OPENID);
                String mOpenIdRegist = Utils.getString(ContectUtils.OPENIDREGIST);
                //如果已经授权了,
                if (TextUtils.isEmpty(mOpenId)||TextUtils.isEmpty(mOpenIdRegist)||!TextUtils.equals(mOpenIdRegist,"123")) {
                    //发起微信登录
                    if (CompontApplayCation.iwxapi != null && CompontApplayCation.iwxapi.isWXAppInstalled()) {
                        SendAuth.Req req = new SendAuth.Req();
                        req.scope = "snsapi_userinfo";
                        req.state = "wechat_sdk_demo_test_neng";
                        CompontApplayCation.iwxapi.sendReq(req);
                    } else {
                        //  Toast.makeText(this, "用户未安装微信", Toast.LENGTH_SHORT).show();
                        ToastMake.showToast("用户未安装微信");

                    }
                    return;

                }else {
                    //直接进行商户支付
                    payPersonal(mOpenId);
                }

            }
        });

        LinearLayoutManager manager = new LinearLayoutManager(WalletActivity.this);
        mRecycleview.setLayoutManager(manager);
        mAdapter = new WalletActivityAdapter(mList);
        mRecycleview.setAdapter(mAdapter);
        if (Utils.netConnected(WalletActivity.this)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    haveMoney();
                }
            }).start();

        }
    }

    private void payPersonal(String mOpenId) {


        Map<String, String> mMoneyMap = new HashMap<>();
        mMoneyMap.put("mch_appid", CompontApplayCation.APP_ID); //公众账号appid
//                    mMoneyMap.put("mchid", MCH_ID); //商户号
        mMoneyMap.put("mchid", "123"); //商户号
//                    mMoneyMap.put("nonce_str", PayUtil.getNonceStr()); //随机字符串
        mMoneyMap.put("nonce_str", "487978"); //随机字符串
//                    mMoneyMap.put("partner_trade_no", PayUtil.getTransferNo()); //商户订单号
        mMoneyMap.put("partner_trade_no", "9c9c9c"); //商户订单号
        mMoneyMap.put("openid", mOpenId); //用户openid
        mMoneyMap.put("check_name", "NO_CHECK"); //校验用户姓名选项 OPTION_CHECK
        //parm.put("re_user_name", "安迪"); //check_name设置为FORCE_CHECK或OPTION_CHECK，则必填
        mMoneyMap.put("amount", "100"); //转账金额
        mMoneyMap.put("desc", "测试转账到个人"); //企业付款描述信息
//                    mMoneyMap.put("spbill_create_ip", PayUtil.getLocalIp(request)); //服务器Ip地址
        mMoneyMap.put("spbill_create_ip", "189.163.12.4"); //服务器Ip地址
//                    mMoneyMap.put("sign", PayUtil.getSign(parm, API_SECRET));
        String sing=MD5.getMapToString(mMoneyMap);
        mMoneyMap.put("sign",sing);
        String json =  Utils.map2XmlString(mMoneyMap);
        //向指定的接口进行请求
        OkHttpUtils
                .postString()
                .url("https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers")
                .content(json)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println("付款失败");
                        System.out.println(call.toString());
                        System.out.println(e.toString());
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println("付款成功");
                        XmlToJson xmlToJson = new XmlToJson.Builder(response).build();
                        System.out.println("xmlToJson"+xmlToJson);
                        PayBeen been=   GsonUtil.parseJsonToBean(xmlToJson.toString(), PayBeen.class);
                        if (been.getXml()!=null){

                        }
                        //查询支付情况
                        payCheck();
                    }
                });


    }

    private void payCheck() {
        Map<String, String> parm = new HashMap<>();
        parm.put("appid",  CompontApplayCation.APP_ID);//申请商户号的appid或商户号绑定的appid
        parm.put("mch_id", "123");//商户号
        parm.put("partner_trade_no", "9c9c9c");//商户订单号
        parm.put("nonce_str", "487978");//随机字符串
        String sing=MD5.getMapToString(parm);
        parm.put("sign", sing);//签名
        String json =  Utils.map2XmlString(parm);
        OkHttpUtils
                .postString()
                .url("https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo")
                .content(json)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        System.out.println("付款查询失败");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println("付款查询成功");
                        XmlToJson xmlToJson = new XmlToJson.Builder(response).build();
                        System.out.println(xmlToJson);
                    }
                });

    }
    private void takeShodle() {
//        CompontApplayCation.phone
        HashMap<String, String> map = new HashMap<>();
        map.put("phone","18221884661");
        String json = GsonUtil.parseMapToJson(map);
        showProgrees(getResources().getString(R.string.string75));
        OkHttpUtils
                .postString()
                .url(UriContect.DRAW)
                .content(json)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        hideProgree();
                        ToastMake.showToast(getResources().getString(R.string.string58));
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        hideProgree();
//                        MesBeen mesBeen = GsonUtil.parseJsonToBean(response, MesBeen.class);
//                        if (mesBeen == null) {
//                            ToastMake.showToast(getResources().getString(R.string.string58));
//                            return;
//                        }
//                        if (!TextUtils.equals(mesBeen.getStatus(), "1")) {
//                            ToastMake.showToast(mesBeen.getMsg());
//                            return;
//                        } else {
//                            ToastMake.showToast(mesBeen.getMsg());
//                        }
                    }
                });


    }

    private void haveMoney() {
        Map<String, String> map = new HashMap<>();
        map.put("phone", CompontApplayCation.phone);
        String json = GsonUtil.parseMapToJson(map);
        mList.clear();
        showProgrees("");
        OkHttpUtils
                .postString()
                .url(UriContect.RECORD)
                .content(json)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        hideProgree();
                        ToastMake.showToast("获取数据失败");
                        Utils.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                mRecycleview.setVisibility(View.VISIBLE);
                                mText.setVisibility(View.GONE);
                            }
                        });
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        hideProgree();
                        final WalletBeen bean = GsonUtil.parseJsonToBean(response, WalletBeen.class);
                        if (bean==null){
                            ToastMake.showToast("获取数据失败");
                            return;
                        }
                        if (!TextUtils.equals(bean.getStatus(),"1")){
                            ToastMake.showToast(bean.getMsg());
                            return;
                        }else {
                            Utils.runOnUIThread(new Runnable() {
                                @Override
                                public void run() {
                                    mMoney.setText(bean.getSum());
                                    List<WalletBeen.DataBean> data = bean.getData();
                                    if(data.size()==0){
                                        mRecycleview.setVisibility(View.GONE);
                                        mText.setVisibility(View.VISIBLE);
                                    }else {
                                        mRecycleview.setVisibility(View.VISIBLE);
                                        mText.setVisibility(View.GONE);
                                        mList.addAll(data);
                                        mAdapter.notifyDataSetChanged();
                                    }
                                }
                            });
                        }
                    }
                });
    }

//    @Override
//    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
//        String accessToken = platform.getDb().getToken(); // 获取授权token
//        String openId = platform.getDb().getUserId(); // 获取用户在此平台的ID
//        String nickname = platform.getDb().getUserName(); // 获取用户昵称
//    }
//
//    @Override
//    public void onError(Platform platform, int i, Throwable throwable) {
//
//    }
//
//    @Override
//    public void onCancel(Platform platform, int i) {
//
//    }
}
